package zd.cornermemory.fragment;

import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.TimerTask;

import greendao.CjDao;
import zd.cornermemory.App;
import zd.cornermemory.R;
import zd.cornermemory.adapter.TextAdapter;
import zd.cornermemory.bean.CoordinateKeyValue;
import zd.cornermemory.bean.CornerOrEdge;
import zd.cornermemory.bean.Cube;
import zd.cornermemory.bean.CubeColor;
import zd.cornermemory.bean.DisplayBean;
import zd.cornermemory.bean.NumberType;
import zd.cornermemory.bean.Probability;
import zd.cornermemory.db.Cj;
import zd.cornermemory.db.GreenDaoManager;
import zd.cornermemory.min2phase.Search;
import zd.cornermemory.min2phase.Tools;
import zd.cornermemory.ui.CjActivity;
import zd.cornermemory.utils.CoordinateUtil;
import zd.cornermemory.utils.FourCube;
import zd.cornermemory.utils.SPUtils;
import zd.cornermemory.utils.SpKey;
import zd.cornermemory.utils.Statistics;
import zd.cornermemory.utils.Timer;
import zd.cornermemory.utils.Utils;
import zd.cornermemory.view.CustomDialog;
import zd.cornermemory.view.TimerDialog;

import static android.content.Context.CLIPBOARD_SERVICE;
import static java.lang.Integer.parseInt;
import static zd.cornermemory.utils.Configs.dip300;
import static zd.cornermemory.utils.Statistics.timeToString;

/**
 * Created by zhud on 2019/4/29.
 */

public class TimerFragment extends Fragment implements View.OnClickListener,View.OnTouchListener{
    public        Timer          timer;
    private TextView tvScramble;	// 显示打乱
    private TextView tvTimer;
    private RelativeLayout scrameble_layout;
    private static Random randomCube          = new Random();
    private        Search cubeSearch = new Search();
    private        zd.cornermemory.threephase.Search cube4 = new zd.cornermemory.threephase.Search();
    private Button       nextButton;
    private Button       bt_scr;
    private Context      mContext;
    private Button       txt_sesname;
    private View         view;
    private ListView     listView;
    private TextAdapter  scrAdapter;
    private PopupWindow  popupWindow;	//打乱弹出窗口
    private boolean      isInputCj;//是否手动输入成绩，默认false
    private boolean      isShowCj;//是否显示成绩简要，默认true
    private boolean isOpenStatus;//是否显示打乱图案，默认false
    private boolean      isLong;//是否长按开始计时，默认false
    private LinearLayout cj_layout;
    private TextView     count;
    private TextView     mo3;
    private TextView     ao5;
    private TextView     ao12;
    private Toast        toast;

    private LinearLayout up_corner_0;
    private LinearLayout up_corner_1;
    private LinearLayout up_corner_2;
    private LinearLayout up_corner_3;
    private LinearLayout up_edge_0;
    private LinearLayout up_edge_1;
    private LinearLayout up_edge_2;
    private LinearLayout up_edge_3;
    private LinearLayout up_edge_4;

    private LinearLayout down_corner_0;
    private LinearLayout down_corner_1;
    private LinearLayout down_corner_2;
    private LinearLayout down_corner_3;
    private LinearLayout down_edge_0;
    private LinearLayout down_edge_1;
    private LinearLayout down_edge_2;
    private LinearLayout down_edge_3;
    private LinearLayout down_edge_4;

    private LinearLayout left_corner_0;
    private LinearLayout left_corner_1;
    private LinearLayout left_corner_2;
    private LinearLayout left_corner_3;
    private LinearLayout left_edge_0;
    private LinearLayout left_edge_1;
    private LinearLayout left_edge_2;
    private LinearLayout left_edge_3;
    private LinearLayout left_edge_4;

    private LinearLayout right_corner_0;
    private LinearLayout right_corner_1;
    private LinearLayout right_corner_2;
    private LinearLayout right_corner_3;
    private LinearLayout right_edge_0;
    private LinearLayout right_edge_1;
    private LinearLayout right_edge_2;
    private LinearLayout right_edge_3;
    private LinearLayout right_edge_4;

    private LinearLayout front_corner_0;
    private LinearLayout front_corner_1;
    private LinearLayout front_corner_2;
    private LinearLayout front_corner_3;
    private LinearLayout front_edge_0;
    private LinearLayout front_edge_1;
    private LinearLayout front_edge_2;
    private LinearLayout front_edge_3;
    private LinearLayout front_edge_4;

    private LinearLayout back_corner_0;
    private LinearLayout back_corner_1;
    private LinearLayout back_corner_2;
    private LinearLayout back_corner_3;
    private LinearLayout back_edge_0;
    private LinearLayout back_edge_1;
    private LinearLayout back_edge_2;
    private LinearLayout back_edge_3;
    private LinearLayout back_edge_4;

    private LinearLayout status_layout;

    private int s4;
    private int s5;
    private int s6;
    private int s7;
    private int s8;
    private int s9;
    private int s10;
    private int s11;
    private int s12;
    private int s13;
    private int s14;
    private int s15;
    private int s16;
    private int s17;
    private int s18;
    private int s19;
    private int s20;

    private Toast toastNo;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.timer_layout, container, false);
        mContext = getActivity();
        toast = Toast.makeText(mContext, getString(R.string.no_input), Toast.LENGTH_SHORT);
        toastNo = Toast.makeText(getActivity(),getString(R.string.no_exist),Toast.LENGTH_SHORT);
        cjDao =  GreenDaoManager.getInstance().getNewSession().getCjDao();
        findViews(view);
        tvTimer.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "timer.ttf"));
        tvScramble.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "scramble.ttf"));
        green = getResources().getColor(R.color.green_text);
        currentPos = SPUtils.getInstance().getInt("currentPos",0);
        setOpenStatus();
        String[] scr = getResources().getStringArray(R.array.scr);
        bt_scr.setText(scr[currentPos]);

        scramble();
        Timer.state = 0;
        timer = new Timer(this);
        setIsInput();
        setIsShowCj();
        setIsLong();
        setCj();
        tvTimer.setOnTouchListener(this);
        nextButton.setOnClickListener(this);
        bt_scr.setOnClickListener(this);
        txt_sesname.setOnClickListener(this);
        tvScramble.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                String scr = tvScramble.getText().toString();
                if(Build.VERSION.SDK_INT > 11) {
                    android.content.ClipboardManager clip = (android.content.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                    clip.setPrimaryClip(ClipData.newPlainText("text", scr));
                }
                else {
                    android.text.ClipboardManager clip = (android.text.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                    clip.setText(scr);
                }
                Toast.makeText(mContext, getString(R.string.copied), Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        mContext.registerReceiver(broadcastReceiver,new IntentFilter(SpKey.NOTIFY_TIMER));
        mContext.registerReceiver(broadcastReceiver,new IntentFilter(SpKey.UPDATE_CJ));
        mContext.registerReceiver(broadcastReceiver,new IntentFilter(SpKey.DELETE_CJ));


        soundPool= new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        s4 = soundPool.load(mContext, R.raw.s4, 1);
        s5 =soundPool.load(mContext, R.raw.s5, 1);
        s6 =soundPool.load(mContext, R.raw.s6, 1);
        s7 =soundPool.load(mContext, R.raw.s7, 1);
        s8 =soundPool.load(mContext, R.raw.s8, 1);
        s9 =soundPool.load(mContext, R.raw.s9, 1);
        s10 =soundPool.load(mContext, R.raw.s10, 1);
        s11 =soundPool.load(mContext, R.raw.s11, 1);
        s12 =soundPool.load(mContext, R.raw.s12, 1);
        s13 =soundPool.load(mContext, R.raw.s13, 1);
        s14 =soundPool.load(mContext, R.raw.s14, 1);
        s15 =soundPool.load(mContext, R.raw.s15, 1);
        s16 =soundPool.load(mContext, R.raw.s16, 1);
        s17 =soundPool.load(mContext, R.raw.s17, 1);
        s18 =soundPool.load(mContext, R.raw.s18, 1);
        s19 =soundPool.load(mContext, R.raw.s19, 1);
        s20 =soundPool.load(mContext, R.raw.s20, 1);



//        insertCj();
        return view;
    }

    private void setOpenStatus() {
        isOpenStatus = SPUtils.getInstance().getBoolean(SpKey.STATUS_IS_OPEN,false);
        if (isOpenStatus) {
            if (currentPos != 8 && currentPos != 9 && currentPos != 10) {//四盲相关不显示打乱图案，暂时没做四阶图案
                status_layout.setVisibility(View.VISIBLE);
            }
        }else{
            status_layout.setVisibility(View.GONE);
        }
    }

    private void findViews(View view) {
        tvScramble = view.findViewById(R.id.tv_scr);
        tvTimer = view.findViewById(R.id.tv_timer);
        nextButton = view.findViewById(R.id.bt_option);
        txt_sesname = view.findViewById(R.id.txt_sesname);
        bt_scr = view.findViewById(R.id.bt_scr);
        scrameble_layout = view.findViewById(R.id.scrameble_layout);
        cj_layout = view.findViewById(R.id.cj_layout);
        count = view.findViewById(R.id.count);
        mo3 = view.findViewById(R.id.mo3);
        ao5 = view.findViewById(R.id.ao5);
        ao12 = view.findViewById(R.id.ao12);

        up_corner_0 = view.findViewById(R.id.up_corner_0);
        up_corner_1 = view.findViewById(R.id.up_corner_1);
        up_corner_2 = view.findViewById(R.id.up_corner_2);
        up_corner_3 = view.findViewById(R.id.up_corner_3);
        up_edge_0 = view.findViewById(R.id.up_edge_0);
        up_edge_1 = view.findViewById(R.id.up_edge_1);
        up_edge_2 = view.findViewById(R.id.up_edge_2);
        up_edge_3 = view.findViewById(R.id.up_edge_3);
        up_edge_4 = view.findViewById(R.id.up_edge_4);

        down_corner_0 = view.findViewById(R.id.down_corner_0);
        down_corner_1 = view.findViewById(R.id.down_corner_1);
        down_corner_2 = view.findViewById(R.id.down_corner_2);
        down_corner_3 = view.findViewById(R.id.down_corner_3);
        down_edge_0 = view.findViewById(R.id.down_edge_0);
        down_edge_1 = view.findViewById(R.id.down_edge_1);
        down_edge_2 = view.findViewById(R.id.down_edge_2);
        down_edge_3 = view.findViewById(R.id.down_edge_3);
        down_edge_4 = view.findViewById(R.id.down_edge_4);


        left_corner_0 = view.findViewById(R.id.left_corner_0);
        left_corner_1 = view.findViewById(R.id.left_corner_1);
        left_corner_2 = view.findViewById(R.id.left_corner_2);
        left_corner_3 = view.findViewById(R.id.left_corner_3);
        left_edge_0 = view.findViewById(R.id.left_edge_0);
        left_edge_1 = view.findViewById(R.id.left_edge_1);
        left_edge_2 = view.findViewById(R.id.left_edge_2);
        left_edge_3 = view.findViewById(R.id.left_edge_3);
        left_edge_4 = view.findViewById(R.id.left_edge_4);

        right_corner_0 = view.findViewById(R.id.right_corner_0);
        right_corner_1 = view.findViewById(R.id.right_corner_1);
        right_corner_2 = view.findViewById(R.id.right_corner_2);
        right_corner_3 = view.findViewById(R.id.right_corner_3);
        right_edge_0 = view.findViewById(R.id.right_edge_0);
        right_edge_1 = view.findViewById(R.id.right_edge_1);
        right_edge_2 = view.findViewById(R.id.right_edge_2);
        right_edge_3 = view.findViewById(R.id.right_edge_3);
        right_edge_4 = view.findViewById(R.id.right_edge_4);

        front_corner_0 = view.findViewById(R.id.front_corner_0);
        front_corner_1 = view.findViewById(R.id.front_corner_1);
        front_corner_2 = view.findViewById(R.id.front_corner_2);
        front_corner_3 = view.findViewById(R.id.front_corner_3);
        front_edge_0 = view.findViewById(R.id.front_edge_0);
        front_edge_1 = view.findViewById(R.id.front_edge_1);
        front_edge_2 = view.findViewById(R.id.front_edge_2);
        front_edge_3 = view.findViewById(R.id.front_edge_3);
        front_edge_4 = view.findViewById(R.id.front_edge_4);

        back_corner_0 = view.findViewById(R.id.back_corner_0);
        back_corner_1 = view.findViewById(R.id.back_corner_1);
        back_corner_2 = view.findViewById(R.id.back_corner_2);
        back_corner_3 = view.findViewById(R.id.back_corner_3);
        back_edge_0 = view.findViewById(R.id.back_edge_0);
        back_edge_1 = view.findViewById(R.id.back_edge_1);
        back_edge_2 = view.findViewById(R.id.back_edge_2);
        back_edge_3 = view.findViewById(R.id.back_edge_3);
        back_edge_4 = view.findViewById(R.id.back_edge_4);
        status_layout = view.findViewById(R.id.status_layout);


    }

    private void insertCj() {//手动造数据

        int minTime = 1000*28;
        int  maxTime = 1000*50;
        Random random = new Random();

        long time = 0L;

        for(int i = 0;i<10000;i++) {
            int s = random.nextInt(maxTime)%(maxTime-minTime+1) + minTime;
            time = s;
            Long date = System.currentTimeMillis()-1000*60*60*4;
            Cj cj = new Cj();
            cj.setDate(date+i*100);
            cj.setSingTime(time);
            cj.setCode("F2 R' D2 R2 U L2 U' R2 D' F2 L2 R2 U' B' L B' F D2 L' D' Rw Uw");
            cj.setStatus(0);
            cj.setGroup(currentPos);
            cjDao.insert(cj);
        }
    }


    private void setIsInput() {
        String isInputStr = SPUtils.getInstance().getString(SpKey.IS_INPUT);
        if(TextUtils.isEmpty(isInputStr)){
            //没有设置过，用默认
            SPUtils.getInstance().put(SpKey.IS_INPUT,"0");
            isInputCj = false;
        }else {
            switch (isInputStr) {
                case "0":
                    isInputCj = false;
                    break;
                case "1":
                    isInputCj = true;
                    break;
            }
        }
        if (isInputCj) {
            tvTimer.setText("IMPORT");
        }else {
            tvTimer.setText("0.000");
        }
    }

    private void setIsShowCj() {
        String isShowCjStr = SPUtils.getInstance().getString(SpKey.IS_SHOW_CJ);
        if(TextUtils.isEmpty(isShowCjStr)){
            //没有设置过，用默认
            SPUtils.getInstance().put(SpKey.IS_SHOW_CJ,"1");
            isShowCj = true;
        }else {
            switch (isShowCjStr) {
                case "0":
                    isShowCj = false;
                    break;
                case "1":
                    isShowCj = true;
                    break;
            }
        }
        if (isShowCj) {
            cj_layout.setVisibility(View.VISIBLE);
        }else {
            cj_layout.setVisibility(View.GONE);
        }
    }

    private void setIsLong() {
        String isLongStr = SPUtils.getInstance().getString(SpKey.IS_LONG);
        if(TextUtils.isEmpty(isLongStr)){
            //没有设置过，用默认
            SPUtils.getInstance().put(SpKey.IS_LONG,"0");
            isLong = false;
        }else {
            switch (isLongStr) {
                case "0":
                    isLong = false;
                    break;
                case "1":
                    isLong = true;
                    break;
            }
        }

    }

    private List<Cj> cjs;
    private CjDao    cjDao;
    //计算成绩ao5 ao12 ..
    private void setCj(){
        List<Cj> temp = App.getInstance().getAllCjMap().get(currentPos);
        if (temp == null) {
            temp = new ArrayList<>();
        }

        cjs = new ArrayList<>();
        cjs.addAll(temp);
        Collections.sort(cjs, new Comparator<Cj>() {
            @Override
            public int compare(Cj cj, Cj t1) {
                return (int)(t1.getId()-cj.getId());
            }
        });
        List<Cj> cjList = new ArrayList<>();
        for (Cj cj : cjs) {
            if (cj.getStatus() != 2) {
                cjList.add(cj);
            }
        }
        count.setText(cjList.size()+"/"+cjs.size());
        setAoX(3);
        setAoX(5);
        setAoX(12);
    }

    private void setAoX(int number) {
        List<Cj> aoList = new ArrayList<>();
        if (cjs.size() < number) {
            if (number == 3) {
                mo3.setText("mo3: N/A");
            }else if(number == 5){
                ao5.setText("ao5: N/A");
            }else {
                ao12.setText("ao12: N/A");
            }
            return;
        }else{
            for(int i = 0;i<number;i++){
                aoList.add(cjs.get(i));
            }

            int dnf = 0;
            for (Cj cj : aoList) {
                if (cj.getStatus() == 2) {
                    dnf++;
                }
            }
            if (dnf > 1) {
                if (number == 3) {
                    mo3.setText("mo3: DNF");
                }else if(number == 5){
                    ao5.setText("ao5: DNF");
                }else{
                    ao12.setText("ao12: DNF");
                }
                return;
            }else if(dnf==1){
                if (number == 3) {
                    mo3.setText("mo3: DNF");
                    return;
                }
                Cj max = null;
                for (Cj cj : aoList) {
                    if (cj.getStatus() == 2) {
                        max = cj;
                        aoList.remove(cj);
                        break;
                    }
                }

                Cj min = Collections.min(aoList);
                aoList.remove(min);
            }else{
                if (number != 3) {
                    Cj min = Collections.min(aoList);
                    Cj max = Collections.max(aoList);
                    aoList.remove(min);
                    aoList.remove(max);
                }
            }

            long avg = 0;
            for (Cj cj : aoList) {
                avg += cj.getSingTime();
            }
            double a = avg/aoList.size();
            avg = Math.round(a);
            String avgStr = timeToString((int) avg);
            if (number == 3) {
                mo3.setText("mo3: "+avgStr);
            }else if(number == 5){
                ao5.setText("ao5: "+avgStr);
            }else {
                ao12.setText("ao12: "+avgStr);
            }

        }
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.equals(SpKey.NOTIFY_TIMER, action)) {
                setIsInput();
                setIsShowCj();
                setIsLong();
                setOpenStatus();
            } else  {
                setCj();
            }
        }
    };

    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 11:
                    if (Timer.state == 0) {
                        if (mCurrentTime > 500) {
                            isOk = true;
                            setTimerColor(green);
                            try {
                                clockTask.cancel();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            clockTask = null;
                        }
                    }else {
                        isOk = false;
                        try {
                            clockTask.cancel();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        clockTask = null;
                    }
                    break;
                case 22:
                    String disrupt = (String) message.obj;
                    showCube(disrupt);
                    break;
                case 33:
                    String result = (String) message.obj;
                    showCube(result);
                    break;
            }
            return true;
        }
    });


    private void hide() {
        tvScramble.setVisibility(View.GONE);
        scrameble_layout.setVisibility(View.GONE);
        cj_layout.setVisibility(View.GONE);
        status_layout.setVisibility(View.GONE);
    }

    private void show() {
        tvScramble.setVisibility(View.VISIBLE);
        scrameble_layout.setVisibility(View.VISIBLE);
        if (isShowCj) {
            cj_layout.setVisibility(View.VISIBLE);
        }
        if (isOpenStatus) {
            status_layout.setVisibility(View.VISIBLE);
        }
    }


    private void scramble() {
        tvScramble.setText(getString(R.string.dl_));
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Probability corner;
                Probability edge;
                String result = "";
                Cube cube = new Cube();
                cube.init();
                switch (currentPos) {
                    case 0://随机三盲
                        result = cubeSearch.solution(Tools.randomCube(), true, randomCube);
                        break;
                    case 1://棱块训练
                        result = cubeSearch.solution(Tools.randomCornerSolved(), 21, 10000, 100, 2);
                        break;
                    case 2://角块训练
                        result = cubeSearch.solution(Tools.randomEdgeSolved(), 21, 10000, 100, 2);
                        break;
                    case 3://神打
                        cube.handleShenType();
                        result = scramble(cube);
                        break;
                    case 4://噩梦
                        cube.handleEmType();
                        result = scramble(cube);
                        break;
                    case 5://绝处逢生
                        Random random = new Random();
                        int r = random.nextInt(10);
                        if (r <= 1) {
                            cube.handleShenType();
                        } else {
                            cube.handleEmType();
                        }
                        result = scramble(cube);
                        break;
                    case 6://笑里藏刀
                        Random random3 = new Random();
                        int r3 = random3.nextInt(10);
                        if (r3 <= 1) {
                            cube.handleEmType();
                        } else {
                            cube.handleShenType();
                        }
                        result = scramble(cube);
                        break;
                    case 7://冰火两重天
                        Random random4 = new Random();
                        int r4 = random4.nextInt(2);
                        if (r4 == 1) {
                            cube.handleShenType();
                        } else {
                            cube.handleShenType();
                        }
                        result = scramble(cube);
                        break;
                    case 8://四盲中心
                        result = cube4.solution(FourCube.getPhaseStr(true));
                        break;
                    case 9://四盲翼棱
                        result = cube4.solution(FourCube.getPhaseStr(false));
                        break;
                    case 10://四盲
                        result = cube4.randomState(randomCube);
                        break;
                    case 11://自定义
                        initDisrupt();
                        break;
                }
                if (currentPos == 11) {
                    return;
                }
                showCube(result);

            }
        });

    }

    private void showCube(String result) {
        currentCode = Statistics.getFormatCodes(result);
        tvScramble.setText(currentCode);
        if (currentPos == 8 || currentPos == 9 || currentPos == 10) {
            status_layout.setVisibility(View.GONE);
        }else{
            setOpenStatus();
        }
        Cube showCube = new Cube();
        showCube.init();
        showCube.disrupt(currentCode);
        List<DisplayBean> displayBeanList =  showCube.getCubeColorStatusData();
        show(displayBeanList);
    }

    private String currentCode;//当前的打乱公式

    private String scramble(Cube cube) {
        CoordinateKeyValue keyValue = CoordinateUtil.coordinateKeyValues.get(new Random().nextInt(CoordinateUtil.coordinateKeyValues.size()));
        cube.disrupt(keyValue.getDisrupt());
        String phaseStr2 = cube.get2phaseStr();
        String result2 = new Search().solution(phaseStr2, 21, 100000000, 0, Search.INVERSE_SOLUTION);
        String disrupt = result2+keyValue.getDisplay();
        return disrupt;

    }


    private void darkenBackground(Float bgcolor) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgcolor;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);
    }

        @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_option:
                scramble();
                break;
            case R.id.bt_scr:
                int resId = R.layout.pop_window;
                view = LayoutInflater.from(mContext).inflate(resId, null);
                listView = (ListView) view.findViewById(R.id.list);
                String[] scr = getResources().getStringArray(R.array.scr);
                scrAdapter = new TextAdapter(mContext, scr, currentPos);
                listView.setAdapter(scrAdapter);
                listView.setSelection(currentPos);
                listView.setOnItemClickListener(listener);

                popupWindow = new PopupWindow(view, dip300, dip300, true);
                popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.choosearea_bg_mid));
                popupWindow.setTouchable(true);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        darkenBackground(1f);
                    }
                });
                popupWindow.showAsDropDown(v, (bt_scr.getWidth()-popupWindow.getWidth())/2, 0);
                darkenBackground(0.5f);
                break;
            case R.id.txt_sesname:
                Intent intent = new Intent(mContext, CjActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("currentPos",currentPos);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

    private int currentPos = 0;
    private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (currentPos != i) {
                currentPos = i;
                scramble();
            }
            currentPos = i;
            SPUtils.getInstance().put("currentPos",currentPos);
            String[] scr = getResources().getStringArray(R.array.scr);
            bt_scr.setText(scr[currentPos]);
            popupWindow.dismiss();
            setCj();
        }
    };

    private boolean isShowDialog;//是否正在显示 处理惩罚弹框
    private float x = 0;
    private float y = 0;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(!isShowDialog){
            switch ( event.getAction() ){
                case MotionEvent.ACTION_DOWN:
                    x = event.getX();
                    y = event.getY();
                    isLeftFling = false;
                    isUpFling = false;
                    touchDown();
                    break;
                case MotionEvent.ACTION_UP:
                    touchUp();
                    break;
                case MotionEvent.ACTION_CANCEL:
                    touchUp();
                    break;
                case MotionEvent.ACTION_MOVE:
                    if(Math.abs(event.getX()-x)>150){
                        isLeftFling = true;
                        setTimerColor(getResources().getColor(R.color.black));
                    }else if(Math.abs(event.getY()-y)>150){
                        isUpFling = true;
                        setTimerColor(getResources().getColor(R.color.black));
                    }

                    break;
            }

        }
        return true;
    }

    public void onKeyDown(){
        if (Timer.state == 1) {
            clocking();
            showCjDialog();
        }
    }


    private EditText editText;
    private void touchUp() {
        if (Timer.state == 0) {
            setTimerColor(getResources().getColor(R.color.black));
            if (isLeftFling) {
                //左右轻扫之后，生成新打乱
                String isLeftStr = SPUtils.getInstance().getString(SpKey.IS_LEFT);
                if (TextUtils.isEmpty(isLeftStr)||TextUtils.equals("1",isLeftStr)) {
                    scramble();
                }
                return;
            }else if(isUpFling){
                //上下轻扫之后，输入成绩
                String isUpStr = SPUtils.getInstance().getString(SpKey.IS_UP);
                if (TextUtils.isEmpty(isUpStr)|| TextUtils.equals("1",isUpStr)) {
                    inputCj();
                }
                return;
            }

            if (isInputCj) {
                inputCj();
                return;
            }

           if(isLong&&!isOk){
               try {
                   clockTask.cancel();
               } catch (Exception e) {
                   e.printStackTrace();
               }
               clockTask = null;
               return;
           }

            Timer.state = 1;
            isPlay = false;
            timer.count2();
            hide();
            acquireWakeLock();
        } else if (Timer.state == 3) {
            showCjDialog();

        }
    }

    int green;
    private void touchDown() {
        if (Timer.state == 0) {//开始计时前 变绿
            if (isLong&&!isInputCj) {
                setTimerColor(getResources().getColor(R.color.colorAccent));
                isOk = false;
                mStartTime = System.currentTimeMillis();
                clockTask = new ClockTask();
                myTimer = new java.util.Timer();
                myTimer.schedule(clockTask, 0, 17);
            }else {
                setTimerColor(green);
            }

        } else if (Timer.state == 1) {//正在计时
            clocking();
        } else if (Timer.state == 3) {
            setTimerColor(green);
            Timer.state = 0;
        }
    }

    private void showCjDialog() {
        isShowDialog = true;
        show();
        Timer.state = 0;
        setTimerColor(getResources().getColor(R.color.black));
        Long t = timer.getTime();
        String ti = Statistics.timeToString(t.intValue());
        dialog = new TimerDialog.Builder(mContext);
        dialog.setTimerStr(getString(R.string.time) + ti);
        dialog.setmOnClickListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                isShowDialog = false;
                Long time = timer.getTime();
                if (i == 1) {
                    time+=2000;
                }
                if (i != 3) {
                    saveCj(i, time);
                }else{
                    scramble();
                }
            }
        });
        dialog.show();
    }

    private TimerDialog.Builder dialog;
    //保存当前成绩
    private void saveCj(int which, Long time) {
        if (which == 2) {
            //DNF 需要同步打乱公式至读码
            Intent broadcast = new Intent(SpKey.CJ_DNF);
            broadcast.putExtra("currentCode", currentCode);
            mContext.sendBroadcast(broadcast);
        }


        Long date = System.currentTimeMillis();
        Cj cj = new Cj();
        cj.setDate(date);
        cj.setSingTime(time);
        cj.setCode(currentCode);
        cj.setStatus(which);
        cj.setGroup(currentPos);
        cjDao.insert(cj);
        List<Cj> cjList = App.getInstance().getAllCjMap().get(currentPos);
        if (cjList == null) {
            cjList = new ArrayList<>();
            App.getInstance().getAllCjMap().put(currentPos, cjList);
        }
        cjList.add(cj);

        setCj();//用于显示成绩简要
        scramble();
    }

    private void inputCj() {
        LayoutInflater factory = LayoutInflater.from(mContext);
        int layoutId = R.layout.editbox_layout;
        view = factory.inflate(layoutId, null);
        editText = (EditText) view.findViewById(R.id.edit_text);
        new CustomDialog.Builder(mContext).setTitle(getString(R.string.input_time)).setView(view)
                .setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Utils.hideKeyboard(editText);
                    }
                }).setNegativeButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String time = Utils.convertStr(editText.getText().toString());
                if(time.equals("Error") || Utils.parseTime(time)==0){
                    toast.show();
                }else{
                    saveCj(0, Utils.parseTime(time));
                    Utils.hideKeyboard(editText);
                }

            }
        }).setNeutralButton("DNF", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String time = Utils.convertStr(editText.getText().toString());
                if(time.equals("Error") || Utils.parseTime(time)==0){
                    toast.show();
                }else{
                    saveCj(2, Utils.parseTime(time));
                    Utils.hideKeyboard(editText);
                }
            }
        }).show();
        Utils.showKeyboard(editText);
    }

    private void clocking() {
        setTimerColor(getResources().getColor(R.color.black));
        Timer.state = 3;
        timer.count2();
    }

    private long mStartTime;
    private long mCurrentTime;
    private boolean isOk;
    private ClockTask clockTask;
    private java.util.Timer myTimer;
    private boolean isPlay;
    private class ClockTask extends TimerTask {
        @Override
        public void run() {
            mCurrentTime = System.currentTimeMillis() - mStartTime;
            mHandler.sendEmptyMessage(11);
        }
    }

    public void setTimerColor(int color) {
        tvTimer.setTextColor(color);
    }
    public void setTimerText(String str) {
        tvTimer.setText(str);
        int sounds = SPUtils.getInstance().getInt(SpKey.TIMER_SOUND, 0);
        if (sounds != 0) {
            Long t = timer.getTime();
            int s = getSoundS(sounds)*1000-500;
            if(t>=s&&!isPlay){
                isPlay = true;
                soundPool.play(getSound(sounds), 1, 1, 0, 0, 1);
            }
        }

    }
    private SoundPool soundPool;

    private int getSound(int sounds){
        switch (sounds) {
            case 1:
                return s4;
            case 2:
                return s5;
            case 3:
                return s6;
            case 4:
                return s7;
            case 5:
                return s8;
            case 6:
                return s9;
            case 7:
                return s10;
            case 8:
                return s11;
            case 9:
                return s12;
            case 10:
                return s13;
            case 11:
                return s14;
            case 12:
                return s15;
            case 13:
                return s16;
            case 14:
                return s17;
            case 15:
                return s18;
            case 16:
                return s19;
            case 17:
                return s20;

        }
        return s20;
    }

    private int getSoundS(int sounds){
        switch (sounds) {
            case 1:
                return 4;
            case 2:
                return 5;
            case 3:
                return 6;
            case 4:
                return 7;
            case 5:
                return 8;
            case 6:
                return 9;
            case 7:
                return 10;
            case 8:
                return 11;
            case 9:
                return 12;
            case 10:
                return 13;
            case 11:
                return 14;
            case 12:
                return 15;
            case 13:
                return 16;
            case 14:
                return 17;
            case 15:
                return 18;
            case 16:
                return 19;
            case 17:
                return 20;

        }
        return 20;
    }

    private void acquireWakeLock() {
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private boolean isLeftFling;//是否左右拖动
    private boolean isUpFling;//是否上下拖动

    private void show(List<DisplayBean> displayBeanList){
        for (DisplayBean displayBean:displayBeanList) {
            switch (displayBean.getCubeDirection()){
                case UP:
                    up_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    up_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    up_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    up_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    up_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    up_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    up_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    up_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    up_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case DOWN:
                    down_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    down_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    down_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    down_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    down_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    down_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    down_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    down_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    down_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case LEFT:
                    left_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    left_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    left_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    left_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    left_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    left_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    left_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    left_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    left_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case RIGHT:
                    right_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    right_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    right_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    right_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    right_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    right_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    right_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    right_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    right_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case FRONT:
                    front_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    front_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    front_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    front_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    front_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    front_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    front_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    front_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    front_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));

                    break;
                case BACK:
                    back_corner_0.setBackground(getDisplayColor(displayBean.getCornerColors().get(0)));
                    back_corner_1.setBackground(getDisplayColor(displayBean.getCornerColors().get(1)));
                    back_corner_2.setBackground(getDisplayColor(displayBean.getCornerColors().get(2)));
                    back_corner_3.setBackground(getDisplayColor(displayBean.getCornerColors().get(3)));

                    back_edge_0.setBackground(getDisplayColor(displayBean.getEdgeColors().get(0)));
                    back_edge_1.setBackground(getDisplayColor(displayBean.getEdgeColors().get(1)));
                    back_edge_2.setBackground(getDisplayColor(displayBean.getEdgeColors().get(2)));
                    back_edge_3.setBackground(getDisplayColor(displayBean.getEdgeColors().get(3)));
                    back_edge_4.setBackground(getDisplayColor(displayBean.getEdgeColors().get(4)));
                    break;
            }
        }
    }

    private Drawable getDisplayColor(CubeColor colorEnum){
        Drawable color = null;
        switch (colorEnum) {
            case YELLOW:
                color = getResources().getDrawable(R.drawable.color_yellow_bg);
                break;
            case WIHTE:
                color = getResources().getDrawable(R.drawable.color_white_bg);
                break;
            case BLUE:
                color = getResources().getDrawable(R.drawable.color_blue_bg);
                break;
            case GREEN:
                color = getResources().getDrawable(R.drawable.color_green_bg);
                break;
            case RED:
                color = getResources().getDrawable(R.drawable.color_red_bg);
                break;
            case ORANGE:
                color = getResources().getDrawable(R.drawable.color_orange_bg);
                break;
        }

        return color;
    }








    private int dlms_type;
    private String cornerCodeLength;
    private String cornerFanseCount;
    private String cornerXunhuanCount;
    private int cornerIshoming;

    private String edgeCodeLength;
    private String edgeFanseCount;
    private String edgeXunhuanCount;
    private int edgeIshoming;
    private int is_parity_all;
    private int is_dl_zb_all;

    /**
     * 反推部分
     */
    private String cornerCode;
    private String cornerFanse;
    private String edgeCode;
    private String edgeFanse;
    private boolean is23;

    private void initDisrupt(){
        dlms_type = SPUtils.getInstance().getInt(SpKey.DL_MS,0);
        cornerCodeLength = SPUtils.getInstance().getString(SpKey.CORNER_CODE_LENGTH,"");
        cornerFanseCount = SPUtils.getInstance().getString(SpKey.CORNER_FANSE_COUNT,"");
        cornerXunhuanCount =SPUtils.getInstance().getString(SpKey.CORNER_XUNHUAN_COUNT,"");
        cornerIshoming = SPUtils.getInstance().getInt(SpKey.CORNER_IS_HOMING, 0);

        edgeCodeLength = SPUtils.getInstance().getString(SpKey.EDGE_CODE_LENGTH,"");
        edgeFanseCount = SPUtils.getInstance().getString(SpKey.EDGE_FANSE_COUNT,"");
        edgeXunhuanCount = SPUtils.getInstance().getString(SpKey.EDGE_XUNHUAN_COUNT,"");
        edgeIshoming = SPUtils.getInstance().getInt(SpKey.EDGE_IS_HOMING, 0);

        is_parity_all = SPUtils.getInstance().getInt(SpKey.IS_PARITY);
        String isDlzb = SPUtils.getInstance().getString(SpKey.IS_DL_ZB,"0");
        is_dl_zb_all = Integer.parseInt(isDlzb);


        cornerCode = SPUtils.getInstance().getString(SpKey.CORNER_CODE,"");
        cornerFanse = SPUtils.getInstance().getString(SpKey.CORNER_FANSE,"");
        edgeCode = SPUtils.getInstance().getString(SpKey.EDGE_CODE,"");
        edgeFanse = SPUtils.getInstance().getString(SpKey.EDGE_FANSE,"");

        cornerCode = cornerCode.replace(" ", "");
        cornerFanse = cornerFanse.replace(" ", "");
        edgeCode = edgeCode.replace(" ", "");
        edgeFanse = edgeFanse.replace(" ", "");




        if (dlms_type == 0) {
            Cube cube = new Cube();
            cube.init();
            int[][] cornerRanges = getRanges(CornerOrEdge.CORNER);
            int[][] edgeRanges = getRanges(CornerOrEdge.EDGE);
            boolean isExist = cube.cubeRandomStatus(cornerRanges,edgeRanges,cornerIshoming,edgeIshoming,is_parity_all);
            if (isExist) {
                toScramble(cube);
            }else {
                toastNo.show();
                return;
            }
        }else if(dlms_type==1){
            randomCodeType();
        }



    }



    private void randomCodeType(){

        if (cornerCode.length() % 2 != edgeCode.length() % 2) {
            tvScramble.setText("");
            toastNo.show();
            return;
        }
        if (cornerFanse.length() > 14) {
            tvScramble.setText("");
            toastNo.show();
            return;
        }
        if (edgeFanse.length() > 22) {
            tvScramble.setText("");
            toastNo.show();
            return;
        }

        if (cornerFanse.length() % 2 != 0 || edgeFanse.length() % 2 != 0) {
            tvScramble.setText("");
            toastNo.show();
            return;
        }

        if (cornerCode.length() == 0 && cornerFanse.length() == 0 && edgeCode.length() == 0 && edgeFanse.length() == 0) {
            tvScramble.setText("");
            return;
        }


        if (cornerFanse.length() >= 10 && edgeFanse.length() > 10) {
            is23 = true;
        }else {
            is23 = false;
        }

        Cube cube = new Cube();
        cube.init();
        String result = cube.codeType(cornerCode.toUpperCase(), cornerFanse.toUpperCase(), edgeCode.toUpperCase(), edgeFanse.toUpperCase());
        if (result != null) {
            tvScramble.setText("");
            toastNo.show();
            return;
        }
        toScramble(cube);
    }




    private void toScramble(final Cube cube) {
        tvScramble.setText(getString(R.string.generate_));
        new Thread(new Runnable() {
            @Override
            public void run() {
                scramble2(cube);
            }
        }).start();
    }

    private void scramble2(Cube cube) {
        String phaseStr = cube.get2phaseStr();
        int step = 21;
        if (is23) {
            step = 23;
        }
        String result = new Search().solution(phaseStr, step, 100000000, 0, Search.INVERSE_SOLUTION);

        if (result.contains("Error")) {
            tvScramble.setText("Error");
//            mHandler.sendEmptyMessage(11);
            return;
        }

        if (is_dl_zb_all == 0) {//打乱坐标任意
            Random random = new Random();
            int r = random.nextInt(24);
            if (r != 1) {
                dlzb(cube, step);
            }else {
                noDlzb(result);
            }
        } else if (is_dl_zb_all == 1) {//打乱坐标
            dlzb(cube, step);
        }else {//不打乱坐标
            noDlzb(result);
        }

    }

    private void noDlzb(String result) {
        Message message = Message.obtain();
        message.what = 33;
        message.obj = result;
        mHandler.sendMessage(message);
    }

    private void dlzb(Cube cube, int step) {
        CoordinateKeyValue keyValue = CoordinateUtil.coordinateKeyValues.get(new Random().nextInt(CoordinateUtil.coordinateKeyValues.size()));
        cube.disrupt(keyValue.getDisrupt());
        String phaseStr2 = cube.get2phaseStr();
        String result2 = new Search().solution(phaseStr2, step, 100000000, 0, Search.INVERSE_SOLUTION);
        String disrupt = result2+keyValue.getDisplay();
        Message message = Message.obtain();
        message.what = 22;
        message.obj = disrupt;
        mHandler.sendMessage(message);
    }
    /**
     *
     * @param cornerOrEdge 角或棱
     * @return 二维数组 分别表示 编码长度、翻色数量、小循环数量的取值范围
     */
    private int[][] getRanges(CornerOrEdge cornerOrEdge){
        int[] codeLengthRange = getRange(cornerOrEdge, 0);
        int[] fanseLengthRange = getRange(cornerOrEdge, 1);
        int[] xunhuanLengthRange = getRange(cornerOrEdge, 2);

        int[][] range = {codeLengthRange,fanseLengthRange,xunhuanLengthRange};
        return range;
    }


    /**
     *
     * @param cornerOrEdge 角或棱
     * @param position 0 编码长度 1 翻色数量 2 小循环数
     * @return
     */
    private int[] getRange(CornerOrEdge cornerOrEdge,int position){
        int[] range = {};
        switch (cornerOrEdge) {
            case CORNER:
                if (position == 0) {
                    range = getRangeType(cornerCodeLength);
                } else if (position == 1) {
                    range = getRangeType(cornerFanseCount);
                }else {
                    range = getRangeType(cornerXunhuanCount);
                }
                break;
            case EDGE:
                if (position == 0) {
                    range = getRangeType(edgeCodeLength);
                } else if (position == 1) {
                    range = getRangeType(edgeFanseCount);
                }else {
                    range = getRangeType(edgeXunhuanCount);
                }
                break;
        }



        return range;
    }


    private int[] getRangeType(String counts){
        NumberType numberType = getNumberType(counts);
        int[] rangeType = {};
        switch (numberType) {
            case BETWEEN:
                String[] s = counts.split("-");
                int start = Integer.parseInt(s[0]);
                int end = Integer.parseInt(s[1]);
                rangeType = new int[]{start,end};
                break;
            case PLUS:
                String[] plus = counts.split("\\+");
                int startPlus = Integer.parseInt(plus[0]);
                rangeType = new int[]{startPlus,20};
                break;
            case MINUS:
                String[] minus = counts.split("\\-");
                int endMinus = Integer.parseInt(minus[0]);
                rangeType = new int[]{0,endMinus};
                break;
            case NUMBER:
                int count = parseInt(counts);
                rangeType = new int[]{count,count};
                break;
            case NONE:
                rangeType = new int[]{0,20};//不填写则给个最大范围
                break;
        }
        return rangeType;
    }

    private NumberType getNumberType(String code) {
        String between = "(\\d{1,5})(\\-)(\\d{1,5})";
        String plus = "(\\d{1,5})(\\+)";
        String minus = "(\\d{1,5})(\\-)";
        String number = "\\d{1,5}";
        boolean isBetween = code.matches(between);
        boolean isPlus = code.matches(plus);
        boolean isMinus = code.matches(minus);
        boolean isNumber = code.matches(number);
        if (isBetween) {
            return NumberType.BETWEEN;
        } else if (isPlus) {
            return NumberType.PLUS;
        }else if (isMinus) {
            return NumberType.MINUS;
        }else if (isNumber) {
            return NumberType.NUMBER;
        }else {
            return NumberType.NONE;
        }
    }

}
